import useNavigation from "./useNavigation";
import { showToast } from "vant";

const torchActive = ref(false);

export default function useScan() {
  const router = useRouter();

  const { navigateToCheckResult } = useNavigation(); // 使用自定义 Hook
  const onDetect = (detectedCodes: string | any[]) => {
    if (detectedCodes.length > 0) {
      const result = detectedCodes[0];
      navigateToCheckResult(result.rawValue);
    } else {
      showToast("扫码失败");
    }
  };
  const onDecode = (decodedString: any) => {
    // alert(JSON.stringify(`11111:${decodedString}`));
    console.log("解码结果:", decodedString);
  };
  const onCameraReady = (_res: any) => {
    console.log("摄像头准备好了");
  };
  const onError = (error: { name: string }) => {
    if (error.name === "NotAllowedError") {
      // user denied camera access permission
      showToast("用户拒绝相机访问权限");
    } else if (error.name === "NotFoundError") {
      // no suitable camera device installed
      showToast("未安装合适的摄像设备");
    } else if (error.name === "NotSupportedError") {
      // page is not served over HTTPS (or localhost)
      showToast("当前网页没有通过 HTTPS 或 localhost 安全协议提供服务");
    } else if (error.name === "NotReadableError") {
      // maybe camera is already in use
      showToast("相机被占用了)");
    } else if (error.name === "OverconstrainedError") {
      // did you request the front camera although there is none?
      showToast("尝试使用前置摄像头)");
    } else if (error.name === "StreamApiNotSupportedError") {
      showToast("浏览器似乎缺少功能)");
      // browser seems to be lacking features
    }
  };
  const goback = () => {
    router.go(-1);
  };
  function toggleTorch() {
    torchActive.value = !torchActive.value;
  }
  return {
    onDetect,
    onDecode,
    onCameraReady,
    onError,
    torchActive,
    toggleTorch,
    goback,
    
  };
}
